const dayjs = require('dayjs');
const pageHelper = require('../../../config/project_helpers_config').pageHelper;
const cloudHelper = require('../../../config/project_helpers_config').cloudHelper;
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		id: '',
		historyItems: [],
		projectType: '研发项目图谱',
		
		// 筛选选项
		branchOptions: ['显示全部分支', '仅主分支', '仅特性分支'],
		branchFilterIndex: 0,
		showDetailInfo: true, // 默认显示详细信息
		
		// 原始数据
		rawData: [],
		
		// 默认认为所有分支类型都存在
		hasFeatureBranch: true,
		hasHotfixBranch: true,
		hasPackBranch: true,
		
		// Canvas图谱控制
		useCanvasGraph: true,  // 默认使用Canvas图谱
		selectedNode: null,    // 当前选中的节点
		
		// 防止页面滚动
		disableScroll: true,
		
		// 全屏模式
		isFullscreenMode: false, // 是否处于全屏模式
		graphData: null, // 图表数据
		commits: [], // 提交记录
		graphOptions: {}, // 图表配置
		errorInfo: null, // 错误信息
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		// 禁止页面滚动
		wx.pageScrollTo({
			scrollTop: 0,
			duration: 0
		});
		
		// 网络检测
		const net = await getNetworkStatus();
		if (!net.isConnected) {
			wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
		} else if (net.networkType === '2g') {
			wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
		}
		listenNetworkStatus((res) => {
			if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
			else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
		});
		logEvent('page_load', { page: 'plm_research_graph' });
		
		if (!options || !options.id) {
			this.setData({
				isLoad: true,
				errorInfo: '未找到项目ID'
			});
			return;
		}
		
		let id = options.id;
		let title = options.title ? decodeURIComponent(options.title) : '研发项目图谱';
		
		this.setData({
			isLoad: false,
			id,
			projectType: title,
			// 强制显示所有分支类型
			hasFeatureBranch: true,
			hasHotfixBranch: true,
			hasPackBranch: true
		});
		
		// 设置导航栏标题
		wx.setNavigationBarTitle({
			title: '项目图谱-' + title
		});
		
		await this._loadProjectData();
	},
	
	/**
	 * 加载项目数据
	 */
	async _loadProjectData() {
		try {
			// 显示加载提示
			wx.showLoading({
				title: '加载中...',
				mask: true
			});
			
			// 尝试从本地缓存获取项目数据
			const key = `research_project_${this.data.id}`;
			let projectRes = null;
			try {
				const cachedData = wx.getStorageSync(key);
				if (cachedData) {
					projectRes = JSON.parse(cachedData);
				}
			} catch (e) {
				console.error('读取缓存失败', e);
			}
			
			// 如果本地有缓存数据，直接使用
			if (projectRes) {
				// 更新项目标题
				if (projectRes && projectRes.PROJECT_TITLE) {
					this.setData({
						projectType: projectRes.PROJECT_TITLE
					});
				}
				
				// 构建Git Graph风格的数据
				this._buildGraphData(projectRes);
				this.setData({
					isLoad: true
				});
				wx.hideLoading();
				return;
			}
			
			// 如果是本地模拟数据或路由请求失败，使用静态数据
			if (false) { // 移除示例项目逻辑
				this._loadStaticData();
				this.setData({
					isLoad: true
				});
				wx.hideLoading();
				return;
			}
			
			// 尝试云函数请求，如果失败则使用静态数据
			try {
				// 获取项目详情
				projectRes = await cloudHelper.callCloudData('research/detail', {
					id: this.data.id
				});
				
				// 获取项目流程历史
				const flowHistoryRes = await cloudHelper.callCloudData('project_flow/history', {
					projectId: this.data.id
				});
				
				// 更新项目标题
				if (projectRes && projectRes.PROJECT_TITLE) {
					const newTitle = projectRes.PROJECT_TITLE;
					this.setData({
						projectType: newTitle
					});
					
					// 更新导航栏标题
					wx.setNavigationBarTitle({
						title: '项目图谱-' + newTitle
					});
				}
				
				// 构建Git Graph风格的数据
				this._buildGraphData(projectRes);
				this.setData({
					isLoad: true
				});
			} catch (err) {
				console.error('API请求失败，使用静态数据', err);
				this._loadStaticData();
				this.setData({
					isLoad: true,
					errorInfo: 'API请求失败，使用静态数据'
				});
			}
			
			wx.hideLoading();
		} catch (err) {
			console.error('加载项目数据失败', err);
			wx.hideLoading();
			
			// 静态数据演示
			this._loadStaticData();
			this.setData({
				isLoad: true,
				errorInfo: '加载项目数据失败'
			});
		}
	},
	
	/**
	 * 构建图形数据
	 * @param {Object} project 项目数据
	 */
	_buildGraphData(project) {
		const commits = project.flow_history || [];
		const processedData = [];
		const branchMap = new Map(); // 存储分支和对应的列索引
		const parentMap = new Map(); // 存储节点父子关系
		
		// 按日期升序排序(先处理早期提交)
		commits.sort((a, b) => {
			return dayjs(a.date).valueOf() - dayjs(b.date).valueOf();
		});
		
		// 第一遍：建立分支索引和父子关系
		branchMap.set('main', 0); // 主分支默认为第一列
		let currentBranchIndex = 1;
		
		commits.forEach(commit => {
			const branch = commit.branch || 'main';
			
			// 如果是新分支，分配新列
			if (!branchMap.has(branch)) {
				branchMap.set(branch, currentBranchIndex++);
			}
			
			// 建立父子关系(记录每个分支的最后一个提交作为子节点的父节点)
			const parentBranch = commit.parent_branch || 'main';
			if (parentBranch && parentBranch !== branch) {
				// 这是一个分支节点，记录其父节点
				parentMap.set(commit.id, parentBranch);
			}
		});
		
		// 第二遍：生成节点数据
		const branchHeads = new Map(); // 记录每个分支的最新提交
		const branchTails = new Map(); // 记录每个分支的首次提交
		const branchNodes = new Map(); // 记录每个分支的所有节点
		
		commits.forEach(commit => {
			const branch = commit.branch || 'main';
			const branchIndex = branchMap.get(branch);
			const parentBranch = parentMap.get(commit.id);
			const parentBranchIndex = parentBranch ? branchMap.get(parentBranch) : 0;
			
			const node = {
				id: commit.id,
				description: commit.description,
				date: commit.date,
				operator: commit.operator,
				stateId: commit.state_id,
				color: this._getBranchColor(branch),
				branch: branch,
				nodeType: parentBranch ? 'branch' : 'commit',
				branchIndex: branchIndex,
				hasBranch: !!parentBranch,
				parentBranch: parentBranch,
				parentBranchIndex: parentBranchIndex, // 记录父分支索引
				connections: []
			};
			
			// 记录分支的所有节点
			if (!branchNodes.has(branch)) {
				branchNodes.set(branch, []);
			}
			branchNodes.get(branch).push(node);
			
			// 记录当前分支的最新提交
			if (!branchHeads.has(branch)) {
				branchTails.set(branch, node); // 记录分支的首个提交
			}
			branchHeads.set(branch, node);
			
			// 如果是分支节点，添加与父分支的连接
			if (parentBranch) {
				const parentNode = branchHeads.get(parentBranch);
				if (parentNode) {
					// 分支连接线 - 从父分支到当前节点
					node.connections.push({
						type: 'branch',
						from: parentNode.id,
						to: node.id,
						fromIndex: branchMap.get(parentBranch),
						toIndex: branchIndex,
						color: this._getBranchColor(branch),
						style: 'branch-line'
					});
				}
			}
			
			// 如果同分支有前一个提交，添加与前一个提交的连接
			const prevNode = branchHeads.get(branch);
			if (prevNode && prevNode.id !== node.id) {
				// 垂直连接线 - 连接同一分支的节点
				node.connections.push({
					type: 'line',
					from: prevNode.id,
					to: node.id,
					fromIndex: branchIndex,
					toIndex: branchIndex,
					color: this._getBranchColor(branch),
					style: 'commit-line'
				});
			}
			
			processedData.push(node);
		});
		
		// 第三遍：处理合并关系
		const merges = [];
		project.merge_history?.forEach(merge => {
			if (merge.from_branch && merge.to_branch && merge.date) {
				const fromNode = branchHeads.get(merge.from_branch);
				const toNode = branchHeads.get(merge.to_branch);
				
				if (fromNode && toNode) {
					// 创建合并节点
					const mergeNode = {
						id: `merge_${fromNode.id}_${toNode.id}`,
						description: `合并从 ${merge.from_branch} 到 ${merge.to_branch}`,
						date: merge.date,
						operator: merge.operator || toNode.operator,
						stateId: merge.id || 'merge',
						color: this._getBranchColor(merge.to_branch),
						branch: merge.to_branch,
						nodeType: 'merge',
						branchIndex: branchMap.get(merge.to_branch),
						mergeBranch: merge.from_branch,
						connections: []
					};
					
					// 垂直连接线 - 从目标分支到合并节点
					mergeNode.connections.push({
						type: 'line',
						from: toNode.id,
						to: mergeNode.id,
						fromIndex: branchMap.get(merge.to_branch),
						toIndex: branchMap.get(merge.to_branch),
						color: this._getBranchColor(merge.to_branch),
						style: 'commit-line'
					});
					
					// 合并连接线 - 从源分支到目标分支
					mergeNode.connections.push({
						type: 'merge',
						from: fromNode.id,
						to: mergeNode.id,
						fromIndex: branchMap.get(merge.from_branch),
						toIndex: branchMap.get(merge.to_branch),
						color: this._getBranchColor(merge.from_branch),
						style: 'merge-line'
					});
					
					merges.push(mergeNode);
					
					// 更新目标分支的头节点
					branchHeads.set(merge.to_branch, mergeNode);
				}
			}
		});
		
		// 合并所有节点并按日期降序重新排序(最新的在前)
		const allNodes = [...processedData, ...merges];
		allNodes.sort((a, b) => {
			return dayjs(b.date).valueOf() - dayjs(a.date).valueOf();
		});
		
		// 标记每个分支的最新节点
		const latestNodeIds = new Set();
		branchHeads.forEach((node) => {
			latestNodeIds.add(node.id);
		});
		
		allNodes.forEach(node => {
			// 标记是否是分支的最新节点
			node.isLatestNode = latestNodeIds.has(node.id);
			
			// 预处理连接线类型，小程序不支持在wx:for中使用filter
			if (node.connections && node.connections.length > 0) {
				node.lineConnections = node.connections.filter(c => c.type === 'line');
				node.branchConnections = node.connections.filter(c => c.type === 'branch');
				node.mergeConnections = node.connections.filter(c => c.type === 'merge');
			} else {
				node.lineConnections = [];
				node.branchConnections = [];
				node.mergeConnections = [];
			}
		});
		
		this.setData({
			historyItems: allNodes,
			rawData: [...allNodes],
			hasFeatureBranch: Array.from(branchMap.keys()).some(b => b.includes('feature')),
			hasHotfixBranch: Array.from(branchMap.keys()).some(b => b.includes('hotfix') || b.includes('faster')),
			hasPackBranch: Array.from(branchMap.keys()).some(b => b.includes('pack')),
			graphData: allNodes,
			commits: commits,
			graphOptions: {
				branchMap: branchMap,
				branchHeads: branchHeads,
				branchTails: branchTails,
				branchNodes: branchNodes,
				processedData: processedData,
				merges: merges,
				allNodes: allNodes
			}
		});
	},
	
	/**
	 * 获取分支颜色
	 * @param {String} branch 分支名称
	 * @returns {String} 分支颜色
	 */
	_getBranchColor(branch) {
		if (!branch || branch === 'main') return '#3b8eea'; // 主分支蓝色
		if (branch.includes('hotfix') || branch === 'faster') return '#ff5252'; // 修复分支红色
		if (branch.includes('feature')) return '#26a69a'; // 功能分支绿色
		if (branch.includes('pack')) return '#f28c35'; // 打包分支橙色
		
		// 如果是其他分支，根据分支名生成稳定颜色
		let hash = 0;
		for (let i = 0; i < branch.length; i++) {
			hash = branch.charCodeAt(i) + ((hash << 5) - hash);
		}
		
		let color = '#';
		for (let i = 0; i < 3; i++) {
			const value = (hash >> (i * 8)) & 0xFF;
			color += ('00' + value.toString(16)).substr(-2);
		}
		
		return color;
	},
	
	/**
	 * 获取状态颜色(原方法重命名)
	 */
	_getStateColor(stateId) {
		// ... 原有逻辑保持不变
	},
	
	/**
	 * 加载静态演示数据
	 * 用于无法连接数据库或数据结构不兼容时提供演示效果
	 */
	_loadStaticData() {
		// 返回空数据
		this.setData({
			historyItems: [],
			rawData: [],
			projectType: '未命名项目',
			hasFeatureBranch: false,
			hasHotfixBranch: false,
			hasPackBranch: false
		});
	},
	
	/**
	 * 格式化日期
	 * @param {Date} date 日期对象
	 * @returns {String} 格式化后的日期字符串
	 */
	_formatDate(date) {
		if (!date || !(date instanceof Date)) return '未知时间';
		
		const year = date.year();
		const month = (date.month() + 1).format("YYYY-MM-DD HH:mm:ss").padStart(2, '0');
		const day = date.date().format("YYYY-MM-DD HH:mm:ss").padStart(2, '0');
		const hour = date.hour().format("YYYY-MM-DD HH:mm:ss").padStart(2, '0');
		const minute = date.minute().format("YYYY-MM-DD HH:mm:ss").padStart(2, '0');
		
		return `${year}-${month}-${day} ${hour}:${minute}`;
	},
	
	/**
	 * 切换详细信息显示
	 */
	toggleDetailInfo: function() {
		this.setData({
			showDetailInfo: !this.data.showDetailInfo
		});
		
		// 获取Canvas组件实例
		const gitGraph = this.selectComponent('#gitGraph');
		if (gitGraph) {
			// 设置详细信息显示标志
			gitGraph.setData({
				showDetailLabels: this.data.showDetailInfo
			});
			
			// 重新绘制图谱
			gitGraph._drawGraph();
		}
	},
	
	/**
	 * 分支筛选变更事件
	 */
	onBranchFilterChange: function(e) {
		const branchFilterIndex = parseInt(e.detail.value);
		
		this.setData({
			branchFilterIndex
		});
		
		// 应用筛选器
		this._applyFilters();
	},
	
	/**
	 * 应用筛选器
	 */
	_applyFilters: function() {
		const { branchFilterIndex, showDetailInfo, rawData } = this.data;
		
		let filteredItems = [...rawData];
		
		// 按分支类型筛选
		if (branchFilterIndex === 1) {
			// 仅主分支
			filteredItems = filteredItems.filter(item => item.branchIndex === 0);
		} else if (branchFilterIndex === 2) {
			// 仅功能分支（所有非主分支）
			filteredItems = filteredItems.filter(item => item.branchIndex > 0);
		}
		
		// 确保始终是最新的记录在顶部
		filteredItems.sort((a, b) => {
			return dayjs(b.date).valueOf() - dayjs(a.date).valueOf();
		});
		
		this.setData({
			historyItems: filteredItems
		});
	},
	
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 * 已禁用下拉刷新，此方法不再使用
	 */
	/*
	onPullDownRefresh: function () {
		// 重新加载数据
		this._loadProjectData(this.data.id);
		
		setTimeout(() => {
			wx.stopPullDownRefresh();
		}, 500);
	},
	*/

	/**
	 * 页面初次渲染完成
	 */
	onReady: function() {
		// 如果使用Canvas图谱，初始化组件
		if (this.data.useCanvasGraph) {
			this._initGitGraphCanvas();
		}
	},
	
	/**
	 * 初始化Git Graph Canvas组件
	 */
	_initGitGraphCanvas: function() {
		// 获取组件实例
		this.gitGraphCanvas = this.selectComponent('#gitGraph');
		
		// 确保组件已经初始化完成
		if (!this.gitGraphCanvas) {
			setTimeout(() => this._initGitGraphCanvas(), 100);
			return;
		}
		
		// 设置详细信息显示状态
		this.gitGraphCanvas.setData({
			showDetailLabels: this.data.showDetailInfo
		});
		
		console.log('Git Graph Canvas组件已初始化');
	},
	
	/**
	 * 处理节点选中事件
	 */
	onNodeSelect: function(e) {
		const node = e.detail.node;
		if (!node) return;
		
		console.log('节点被选中:', node);
		
		// 更新选中节点
		this.setData({
			selectedNode: node
		});
	},
	
	/**
	 * 切换图谱显示模式
	 */
	toggleGraphMode: function() {
		this.setData({
			useCanvasGraph: !this.data.useCanvasGraph
		});
		
		// 如果切换到Canvas模式，确保组件已初始化
		if (this.data.useCanvasGraph) {
			this._initGitGraphCanvas();
		}
	},
	
	/**
	 * 处理导出成功事件
	 */
	onExportSuccess: function(e) {
		console.log('导出成功:', e.detail);
		wx.showToast({
			title: '导出成功',
			icon: 'success',
			duration: 2000
		});
	},
	
	/**
	 * 处理页面鼠标滚轮事件 - 将事件传递给Canvas组件
	 */
	onPageWheel: function(e) {
		// 获取Canvas组件实例
		const gitGraph = this.selectComponent('#gitGraph');
		if (gitGraph) {
			// 将滚轮事件传递给组件
			gitGraph.onWheelScroll(e);
		}
	},
	
	/**
	 * 处理页面触摸开始事件
	 */
	onPageTouchStart: function(e) {
		// 获取Canvas组件实例
		const gitGraph = this.selectComponent('#gitGraph');
		if (gitGraph) {
			// 将触摸事件传递给组件
			gitGraph.onTouchStart(e);
		}
	},
	
	/**
	 * 处理页面触摸移动事件
	 */
	onPageTouchMove: function(e) {
		// 获取Canvas组件实例
		const gitGraph = this.selectComponent('#gitGraph');
		if (gitGraph) {
			// 将触摸事件传递给组件
			gitGraph.onTouchMove(e);
		}
	},
	
	/**
	 * 处理页面触摸结束事件
	 */
	onPageTouchEnd: function(e) {
		// 获取Canvas组件实例
		const gitGraph = this.selectComponent('#gitGraph');
		if (gitGraph) {
			// 将触摸事件传递给组件
			gitGraph.onTouchEnd(e);
		}
	},
	
	/**
	 * 禁止页面滚动
	 */
	onPageScroll: function(e) {
		if (this.data.disableScroll) {
			wx.pageScrollTo({
				scrollTop: 0,
				duration: 0
			});
		}
	},

	/**
	 * 分享给朋友
	 */
	onShareAppMessage: function() {
		return {
			title: this.data.projectType,
			imageUrl: '',
			path: '/pages/project_graph/research_graph?id=' + this.data.id
		}
	},

	/**
	 * 处理全屏模式变化
	 * @param {Object} e 事件对象
	 */
	onFullscreenChange: function(e) {
		// 获取全屏状态
		const isFullscreen = e.detail.isFullscreen;
		
		// 更新页面状态
		this.setData({
			isFullscreenMode: isFullscreen
		});
		
		// 处理页面滚动
		if (isFullscreen) {
			// 全屏模式时，禁止页面滚动
			wx.pageScrollTo({
				scrollTop: 0,
				duration: 0
			});
			
			// 设置页面样式，防止滚动
			this.setData({
				disableScroll: true
			});
		} else {
			// 退出全屏模式后，允许页面滚动
			this.setData({
				disableScroll: false
			});
		}
	},

	/**
	 * 切换全屏显示模式
	 */
	toggleFullscreen: function() {
		const isFullscreen = !this.data.isFullscreenMode;
		
		// 更新页面状态
		this.setData({
			isFullscreenMode: isFullscreen
		});
		
		// 获取Canvas组件并触发全屏切换
		const gitGraph = this.selectComponent('#gitGraph');
		if (gitGraph) {
			gitGraph.toggleFullscreen();
		}
		
		// 处理页面滚动
		if (isFullscreen) {
			// 全屏模式时，禁止页面滚动
			wx.pageScrollTo({
				scrollTop: 0,
				duration: 0
			});
			
			// 设置页面样式，防止滚动
			this.setData({
				disableScroll: true
			});
		} else {
			// 退出全屏模式后，允许页面滚动
			this.setData({
				disableScroll: false
			});
		}
		
		// 显示提示
		wx.showToast({
			title: isFullscreen ? '进入全屏模式' : '退出全屏模式',
			icon: 'none',
			duration: 1500
		});
	},
	
	/**
	 * 重置视图
	 */
	resetView: function() {
		// 获取Canvas组件并调用其重置方法
		const gitGraph = this.selectComponent('#gitGraph');
		if (!gitGraph) {
			pageHelper.showModal('图谱组件未初始化，无法重置视图');
			return;
		}
		
		gitGraph.resetView();
		
		// 显示提示
		wx.showToast({
			title: '已重置视图',
			icon: 'none',
			duration: 1500
		});
	},
	
	/**
	 * 导出图谱为图片
	 */
	exportGraph: function() {
		// 获取Canvas组件并调用其导出方法
		const gitGraph = this.selectComponent('#gitGraph');
		if (!gitGraph) {
			pageHelper.showModal('图谱组件未初始化，无法导出');
			return;
		}
		
		gitGraph.exportGraph();
	}
}); 